package com.github.byakkili.bim.protocol.json;

import cn.hutool.core.bean.BeanUtil;
import com.github.byakkili.bim.core.BimContext;
import com.github.byakkili.bim.core.BimSession;
import com.github.byakkili.bim.core.handler.command.CommandFrame;
import com.github.byakkili.bim.core.handler.command.CommandProcessor;
import com.github.byakkili.bim.core.support.util.CommandProcessorUtils;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.Map;

/**
 * @author Guannian Li
 */
public abstract class BaseJsonCodec<T> extends MessageToMessageCodec<T, CommandFrame> {

    protected CommandFrame convertCommandFrame(BimSession session, int command, Map jsonMap) {
        BimContext context = session.getContext();
        Map<Integer, CommandProcessor> commandHandlers = context.getConfig().getCommandProcessors();

        CommandProcessor commandHandler = commandHandlers.get(command);
        if (commandHandler == null) {
            return new CommandFrame<>(command, null);
        }
        Class<?> msgClass = CommandProcessorUtils.getMsgClass(commandHandler);
        Object jsonMsg = BeanUtil.toBean(jsonMap, msgClass);

        return new CommandFrame<>(command, jsonMsg);
    }
}
